package feishu_msg_robot

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"gopkg.in/resty.v1"
	"time"
)

var SyncMsgRobot = MsgRobotConfig{
	WebHookClient: "https://open.feishu.cn/open-apis/bot/v2/hook/aa47d93d-264f-4718-95ca-a8b1cdcba253",
	SingKey:       "YBNJthkj5YDVvUeIXC6z6d",
}

type MsgRobotConfig struct {
	WebHookClient string `json:"webhook_hook"` // 飞书群创建机器人的webhook地址
	SingKey       string `json:"sing_key"`     // 验签签名
}

type RobotRequest struct {
	TimeStamp string  `json:"timestamp"`
	Sign      string  `json:"sign"`
	MsgType   string  `json:"msg_type"`
	Content   Content `json:"content"`
}

type Content struct {
	Text string `json:"text" `
}

type RobotResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func (rob *MsgRobotConfig) SendMsg(msg string) error {
	ts := time.Now().Unix()
	sign := GenSign(rob.SingKey, ts)

	var req = RobotRequest{
		TimeStamp: fmt.Sprintf("%v", ts),
		Sign:      sign,
		MsgType:   "text",
		Content: Content{
			Text: msg,
		},
	}

	client := resty.New()
	rsp, err := client.R().
		SetHeader("Content-Type", "application/json").
		SetBody(req).
		Post(rob.WebHookClient)
	if err != nil {
		return err
	}

	var resp RobotResponse
	err = json.Unmarshal(rsp.Body(), &resp)
	if err != nil {
		return err
	}

	if resp.Code == 19021 {
		fmt.Println("验签失败")
		return errors.New("验签失败")
	}
	return nil
}

// GenSign 创建签名
func GenSign(secret string, timestamp int64) string {
	// 把timestamp+"\n"+密钥当做签名字符串
	stringToSign := fmt.Sprintf("%v\n%s", timestamp, secret)

	// 使用HmacSHA256算法计算签名
	h := hmac.New(sha256.New, []byte(stringToSign))
	signData := h.Sum(nil)

	// 对签名数据进行Base64编码
	encodedSign := base64.StdEncoding.EncodeToString(signData)
	return encodedSign
}
